package com.example.security2.service;

import com.example.security2.pojo.LoginVO;
import com.example.security2.pojo.MyUserDetails;
import com.example.security2.pojo.Result;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Objects;
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private AuthenticationManager  authenticationManager;
    /*@Resource
    private UserDetailsService        userDetailsService;*/
    @Override
    public Result login(LoginVO loginVO) {
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginVO.getUsername(), loginVO.getPassword());
        // UsernamePasswordAuthenticationToken是Authentication接口的实现类，它包含了用户名和密码
        Authentication authentication1 = null;
        try {
            authentication1 = authenticationManager.authenticate(authentication);
        } catch (AuthenticationException e) {

           return Result.error("登录失败,用户名或密码错误");//应该会用全局异常处理器处理
        }

       /* UserDetails userDetails = (UserDetails) authentication1.getPrincipal();
        String username = userDetails.getUsername();
        String password = userDetails.getPassword();*/

        MyUserDetails myUserDetails = (MyUserDetails) authentication1.getPrincipal();
        String username =myUserDetails.getUsername();
        String password =myUserDetails.getPassword();

        //将用户名加入生成jwt
        String token = "token:"+username+"______"+password;
        return Result.success(token);
    }
}
